package org.xiaohanghu.starter;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collection;

/**
 * @author xiaohanghu
 */
public class JavaCodeLoadUtils {

	/**
	 * 根据指定的文件/路径集合构造新的ClassLoader
	 * 
	 * @param javaResources
	 *            java文件资源。
	 */
	public static ClassLoader loadeJavaFiles(Collection<File> javaFiles) {
		ClassLoader parent = Thread.currentThread().getContextClassLoader();
		return loadeJavaFiles(javaFiles, parent);
	}

	/**
	 * 根据指定的文件/路径集合构造新的ClassLoader
	 * 
	 * @param javaResources
	 *            java文件资源。
	 * @param parent
	 *            父类加载
	 */
	public static ClassLoader loadeJavaFiles(Collection<File> javaFiles,
			ClassLoader parent) {
		int cnt = javaFiles.size();
		URL[] urls = new URL[cnt];
		int i = 0;
		for (File javaFile : javaFiles) {
			try {
				URL javaFileUrl = javaFile.toURI().toURL();
				// URL javaFileUrl = new URL(PathUtils.encodeFileURL(u));
				urls[i] = javaFileUrl;
				i++;
			} catch (MalformedURLException e) {
			}
		}
		/*
		 * if (parent == null) { parent = Classpath.class.getClassLoader(); }
		 */
		if (parent == null) {
			parent = ClassLoader.getSystemClassLoader();
		}
		return new URLClassLoader(urls, parent);
	}

	/**
	 * 根据指定的文件/路径集合构造新的ClassLoader
	 * 
	 * @param javaResources
	 *            java文件资源。
	 * 
	 * @param parent
	 *            父类加载
	 */
	public static ClassLoader loadeJavaResources(Collection<URL> javaResources,
			ClassLoader parent) {
		int cnt = javaResources.size();
		URL[] urls = new URL[cnt];
		int i = 0;
		for (URL url : javaResources) {
			urls[i] = url;
			i++;
		}
		if (parent == null) {
			parent = ClassLoader.getSystemClassLoader();
		}
		return new URLClassLoader(urls, parent);
	}

	public static ClassLoader loadeJavaResourcesByCurrentThread(
			Collection<URL> javaResources) {
		ClassLoader parent = Thread.currentThread().getContextClassLoader();
		ClassLoader classLoader = loadeJavaResources(javaResources, parent);
		Thread.currentThread().setContextClassLoader(classLoader);
		return classLoader;
	}

}
